package com.is.common.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 类转换初始化
 */
public class TUtil {
    public TUtil() {
    }

    public static <T> T getT(Object o, int i) {
        try {
            //getSuperclass()获得该类的父类
            Class clazz = o.getClass();
            //getGenericSuperclass()获得带有泛型的父类
            Type type = clazz.getGenericSuperclass();
            //ParameterizedType参数化类型，即泛型
            ParameterizedType p = (ParameterizedType) type;
            //getActualTypeArguments获取参数化类型的数组，泛型可能有多个
            Class<T> tClass = (Class<T>) p.getActualTypeArguments()[i];
            return tClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Class<?> forName(String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
